package com.open.yujiakj.core.base;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.open.yujiakj.common.exception.BizException;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Field;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * @program: YJ-admin
 * @description:
 * @author: honglei
 * @create: 2022-03-10 17:53
 */
public class BaseServiceImpl<M extends IBaseMapper<T>, T> extends MPJBaseServiceImpl<M,T> implements IBaseService<T>{


    @Override
    public IPage<T> fuzzySearch(String searchText) {
        return IBaseService.super.fuzzySearch(searchText);
    }

    @Override
    public IPage<T> fuzzySearch(String searchText, Integer pageNo, Integer pageSize, boolean isSearchCount) {
        return null;
    }

    @Override
    public IPage<T> selectPage(BaseQuery baseQuery) {
        return IBaseService.super.selectPage(baseQuery);
    }

    @Override
    public IPage<T> selectPage(BaseQuery baseQuery, boolean isSearchCount) {
        return IBaseService.super.selectPage(baseQuery, isSearchCount);
    }

    @Override
    public IPage<T> selectPage(T t, BaseQuery baseQuery, boolean isSearchCount) {
        return IBaseService.super.selectPage(t, baseQuery, isSearchCount);
    }

    @Override
    public IPage<T> selectPage(T t,BaseQuery baseQuery, boolean copyBean, boolean isSearchCount) {
        if (Objects.isNull(t)){
            try {
                t = (T) this.entityClass.newInstance();
                ;
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }

        IPage<T> page = new Page<>(baseQuery.getPageIndex(),baseQuery.getPageSize(),isSearchCount);
        if (Objects.isNull(t)){
            throw new BizException("分页查询参数错误！ T is null !");
        }
        formatBeanEmpty(t);
        if (copyBean){
            BeanUtils.copyProperties(baseQuery,t);
        }

        QueryWrapper<T> queryWrapper= Wrappers.query(t);
        //非等值查询条件填充
        WrapperUtil.getInstance().initQueryToWrapper(queryWrapper,baseQuery);

        IPage<T> iPage = this.baseMapper.selectPage(page,queryWrapper);
        return iPage;
    }


    @Override
    public T selectLimitOne(BaseQuery queryBean) {
        List<T> list=selectList(queryBean);
        if (! CollectionUtils.isEmpty(list)){
            return list.get(0);
        }
        return null;
    }

    @Override
    public List<T> selectList(T t, BaseQuery queryBean) {
        if (Objects.isNull(t)){
            try {
                t = (T) this.entityClass.newInstance();
                ;
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        formatBeanEmpty(t);
        BeanUtils.copyProperties(queryBean,t);

        QueryWrapper<T> queryWrapper= Wrappers.query(t);
        //非等值查询条件填充
        WrapperUtil.getInstance().initQueryToWrapper(queryWrapper,queryBean);

        return Optional.ofNullable(this.baseMapper.selectList(queryWrapper)).orElse(Collections.EMPTY_LIST);
    }

    @Override
    public List<T> selectList(BaseQuery queryBean) {
        return IBaseService.super.selectList(queryBean);
    }


    /**
     * 可能存在业务重复的批量保存
     * @param list
     * @param baseQuery
     * @param repeatMode  重复处理模式(非主键)0 不处理 1 覆盖 2 删除 3 剔除
     * @return
     */
    @Override
    public boolean saveBatchWithRepeat(List<T> list, BaseQuery baseQuery, int repeatMode)  throws Exception{
        if(repeatMode == 0){
            return saveBatch(list);
        }
        if(repeatMode == 1){
            //todo 查询出已存在的，并绑定

            return saveOrUpdateBatch(list);
        }
        if (null !=baseQuery && ! CollectionUtils.isEmpty(baseQuery.getQueryConditions()) ){
            QueryWrapper<T> wrapper = Wrappers.query();
            WrapperUtil.getInstance().initQuery2Wrapper(wrapper,baseQuery.getQueryConditions());
            remove(wrapper);
        }
        return false;
    }

    @Override
    public boolean removeByConditions(T t, BaseQuery queryBean) {
        BeanUtils.copyProperties(queryBean,t);
        QueryWrapper<T> wrapper= Wrappers.query(t);
        WrapperUtil.getInstance().initQuery2Wrapper(wrapper,queryBean.getQueryConditions());
        return remove(wrapper);
    }






    /***
     * 将“”转null 防止意外置空数据库字段
     * ""-->null
     * @param object
     */
    public  void formatBeanEmpty(Object object){
        //获得字节码对象
        Class a = object.getClass();

        Field[] fields = a.getDeclaredFields();
        for (Field f : fields) {
            String type = f.getGenericType().toString();
            String name = f.getName();
            f.setAccessible(true);
            if (type.contains("String")) {
                try {
                    Object value = f.get(object);
                    if (value!=null && "".equals(value.toString())){
                        f.set(object, null);//填充值
                    }
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
